package org.jeecg.modules.demo.sjcjmb.controller;

import org.jeecg.common.system.query.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import java.util.Arrays;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.sjcjmb.entity.YlshSjcjmbsjx;
import org.jeecg.modules.demo.sjcjmb.entity.YlshSjcjmb;
import org.jeecg.modules.demo.sjcjmb.service.IYlshSjcjmbService;
import org.jeecg.modules.demo.sjcjmb.service.IYlshSjcjmbsjxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: ylsh_sjcjmb
 * @Author: jeecg-boot
 * @Date:   2021-12-13
 * @Version: V1.0
 */
@Api(tags="ylsh_sjcjmb")
@RestController
@RequestMapping("/sjcjmb/ylshSjcjmb")
@Slf4j
public class YlshSjcjmbController extends JeecgController<YlshSjcjmb, IYlshSjcjmbService> {

	@Autowired
	private IYlshSjcjmbService ylshSjcjmbService;

	@Autowired
	private IYlshSjcjmbsjxService ylshSjcjmbsjxService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param ylshSjcjmb
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ylsh_sjcjmb-分页列表查询")
	@ApiOperation(value="ylsh_sjcjmb-分页列表查询", notes="ylsh_sjcjmb-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(YlshSjcjmb ylshSjcjmb,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<YlshSjcjmb> queryWrapper = QueryGenerator.initQueryWrapper(ylshSjcjmb, req.getParameterMap());
		Page<YlshSjcjmb> page = new Page<YlshSjcjmb>(pageNo, pageSize);
		IPage<YlshSjcjmb> pageList = ylshSjcjmbService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
     *   添加
     * @param ylshSjcjmb
     * @return
     */
    @AutoLog(value = "ylsh_sjcjmb-添加")
    @ApiOperation(value="ylsh_sjcjmb-添加", notes="ylsh_sjcjmb-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody YlshSjcjmb ylshSjcjmb) {
        ylshSjcjmbService.save(ylshSjcjmb);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     * @param ylshSjcjmb
     * @return
     */
    @AutoLog(value = "ylsh_sjcjmb-编辑")
    @ApiOperation(value="ylsh_sjcjmb-编辑", notes="ylsh_sjcjmb-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody YlshSjcjmb ylshSjcjmb) {
        ylshSjcjmbService.updateById(ylshSjcjmb);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "ylsh_sjcjmb-通过id删除")
    @ApiOperation(value="ylsh_sjcjmb-通过id删除", notes="ylsh_sjcjmb-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        ylshSjcjmbService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "ylsh_sjcjmb-批量删除")
    @ApiOperation(value="ylsh_sjcjmb-批量删除", notes="ylsh_sjcjmb-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.ylshSjcjmbService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YlshSjcjmb ylshSjcjmb) {
        return super.exportXls(request, ylshSjcjmb, YlshSjcjmb.class, "ylsh_sjcjmb");
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YlshSjcjmb.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-ylsh_sjcjmbsjx-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "ylsh_sjcjmbsjx-通过主表ID查询")
	@ApiOperation(value="ylsh_sjcjmbsjx-通过主表ID查询", notes="ylsh_sjcjmbsjx-通过主表ID查询")
	@GetMapping(value = "/listYlshSjcjmbsjxByMainId")
    public Result<?> listYlshSjcjmbsjxByMainId(YlshSjcjmbsjx ylshSjcjmbsjx,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<YlshSjcjmbsjx> queryWrapper = QueryGenerator.initQueryWrapper(ylshSjcjmbsjx, req.getParameterMap());
        Page<YlshSjcjmbsjx> page = new Page<YlshSjcjmbsjx>(pageNo, pageSize);
        IPage<YlshSjcjmbsjx> pageList = ylshSjcjmbsjxService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param ylshSjcjmbsjx
	 * @return
	 */
	@AutoLog(value = "ylsh_sjcjmbsjx-添加")
	@ApiOperation(value="ylsh_sjcjmbsjx-添加", notes="ylsh_sjcjmbsjx-添加")
	@PostMapping(value = "/addYlshSjcjmbsjx")
	public Result<?> addYlshSjcjmbsjx(@RequestBody YlshSjcjmbsjx ylshSjcjmbsjx) {
		ylshSjcjmbsjxService.save(ylshSjcjmbsjx);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param ylshSjcjmbsjx
	 * @return
	 */
	@AutoLog(value = "ylsh_sjcjmbsjx-编辑")
	@ApiOperation(value="ylsh_sjcjmbsjx-编辑", notes="ylsh_sjcjmbsjx-编辑")
	@PutMapping(value = "/editYlshSjcjmbsjx")
	public Result<?> editYlshSjcjmbsjx(@RequestBody YlshSjcjmbsjx ylshSjcjmbsjx) {
		ylshSjcjmbsjxService.updateById(ylshSjcjmbsjx);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ylsh_sjcjmbsjx-通过id删除")
	@ApiOperation(value="ylsh_sjcjmbsjx-通过id删除", notes="ylsh_sjcjmbsjx-通过id删除")
	@DeleteMapping(value = "/deleteYlshSjcjmbsjx")
	public Result<?> deleteYlshSjcjmbsjx(@RequestParam(name="id",required=true) String id) {
		ylshSjcjmbsjxService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "ylsh_sjcjmbsjx-批量删除")
	@ApiOperation(value="ylsh_sjcjmbsjx-批量删除", notes="ylsh_sjcjmbsjx-批量删除")
	@DeleteMapping(value = "/deleteBatchYlshSjcjmbsjx")
	public Result<?> deleteBatchYlshSjcjmbsjx(@RequestParam(name="ids",required=true) String ids) {
	    this.ylshSjcjmbsjxService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportYlshSjcjmbsjx")
    public ModelAndView exportYlshSjcjmbsjx(HttpServletRequest request, YlshSjcjmbsjx ylshSjcjmbsjx) {
		 // Step.1 组装查询条件
		 QueryWrapper<YlshSjcjmbsjx> queryWrapper = QueryGenerator.initQueryWrapper(ylshSjcjmbsjx, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<YlshSjcjmbsjx> pageList = ylshSjcjmbsjxService.list(queryWrapper);
		 List<YlshSjcjmbsjx> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "ylsh_sjcjmbsjx"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, YlshSjcjmbsjx.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("ylsh_sjcjmbsjx报表", "导出人:" + sysUser.getRealname(), "ylsh_sjcjmbsjx"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importYlshSjcjmbsjx/{mainId}")
    public Result<?> importYlshSjcjmbsjx(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<YlshSjcjmbsjx> list = ExcelImportUtil.importExcel(file.getInputStream(), YlshSjcjmbsjx.class, params);
				 for (YlshSjcjmbsjx temp : list) {
                    temp.setSjcjmbId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 ylshSjcjmbsjxService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-ylsh_sjcjmbsjx-end----------------------------------------------*/


	 //动态创建表
	 @RequestMapping("/createTable")
	 public String test2(String Id,String Name){
		 List<YlshSjcjmbsjx> ylshSjcjmbsjx = ylshSjcjmbsjxService.selectAll(Id);
		 String content = "";
		 if (ylshSjcjmbsjx!=null && ylshSjcjmbsjx.size()!=0) {
			 content = "wellId varchar(50) DEFAULT NULL COMMENT '单井Id',wellName varchar(50) DEFAULT NULL COMMENT '单井名称'";
		 	String content1="";
			 for (YlshSjcjmbsjx ylshSjcjmbsjx1 : ylshSjcjmbsjx) {
			 	switch (ylshSjcjmbsjx1.getSjlx()){
					case "int": content1 = ylshSjcjmbsjx1.getWlzdmc() + " " + ylshSjcjmbsjx1.getSjlx() + "(" + ylshSjcjmbsjx1.getSjcd() + ")"; break;
					case "varchar": content1 = ylshSjcjmbsjx1.getWlzdmc() + " " + ylshSjcjmbsjx1.getSjlx() + "(" + ylshSjcjmbsjx1.getSjcd() + ")"; break;
					case "date": content1 = ylshSjcjmbsjx1.getWlzdmc() + " " + ylshSjcjmbsjx1.getSjlx(); break;
					case "double": content1 = ylshSjcjmbsjx1.getWlzdmc() + " " + ylshSjcjmbsjx1.getSjlx() + " (" + ylshSjcjmbsjx1.getSjcd() + ",2)"; break;
					case "tinyint": content1 = ylshSjcjmbsjx1.getWlzdmc() + " " + ylshSjcjmbsjx1.getSjlx() + "(" + ylshSjcjmbsjx1.getSjcd() + ")"; break;
					case "decimal": content1 = ylshSjcjmbsjx1.getWlzdmc() + " " + ylshSjcjmbsjx1.getSjlx() + "(" + ylshSjcjmbsjx1.getSjcd() + ",2)"; break;
				}
				 content1 = ylshSjcjmbsjx1.getSffk()==1? content1 + " DEFAULT NULL  COMMENT '" + ylshSjcjmbsjx1.getSjxmc() +"'":content1 + " NOT NULL  COMMENT '" + ylshSjcjmbsjx1.getSjxmc() +"'";
				 content += content==""? content1:","+content1;
			 }
		 }
		 if (content != ""){
		 	content += ",createBy varchar(50) DEFAULT NULL COMMENT '创建人',\n" +
					"createTime datetime DEFAULT NULL COMMENT '创建时间',\n" +
					"updateBy varchar(50) DEFAULT NULL COMMENT '修改人',\n" +
					"updateTime datetime DEFAULT NULL COMMENT '修改时间'," +
					"states varchar(10) DEFAULT NULL COMMENT '状态'";
		 }
//		 String tableName = "t2";      //mybatis中#() 占位符，对应的变量会自动加上引号   $()  拼接符，对应的变量不会自动加上引号
//		 String name = "  `id` int(11) DEFAULT NULL,
						//  `q` varchar(10) DEFAULT NULL COMMENT '第一',
						//  `w` date NOT NULL COMMENT '第二',
						//  `e` double(10,0) DEFAULT NULL COMMENT '第三',
						//  `r` decimal(10,0) DEFAULT NULL COMMENT '第四',
						//  `t` varchar(0) DEFAULT NULL";     //表中字段名字
		 ylshSjcjmbService.createTable(Name,content);//创建表
		 return "生成成功";
	 }


}
